﻿using CuttingEdge.Conditions;
using Newtonsoft.Json;
using PSAMMatrixCloud.BLL.BizCommon;
using PSAMMatrixCloud.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace PSAMMatrixCloud.BLL.WebAPI
{
    /// <summary>
    /// PSAM加密盒子
    /// </summary>
    public class PSAMDeviceAPIService
    {
        private string IP;
        public PSAMDeviceAPIService(string ClientIP)
        {
            IP = ClientIP;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="userID"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public Common.SimpleResult Add(string appID, string userID, string postData)
        {
            #region CheckParmeter

            Condition.Requires(userID, "userID").IsNotNullOrWhiteSpace();//userID不能为空或者空字符串
            Condition.Requires(postData, "postData").IsNotNullOrWhiteSpace();//postData不能为空或者空字符串

            var modelRe = Newtonsoft.Json.JsonConvert.DeserializeObject<PSAMDeviceModel>(postData);//反序列化json对象
            Condition.Requires(modelRe.MatrixIP, "matrixip").IsNotNullOrWhiteSpace().IsNotLongerThan(100);
            Condition.Requires(modelRe.MatrixNo, "matrixport").IsNotNullOrWhiteSpace().IsNotLongerThan(40);
            Condition.Requires(modelRe.MatrixNo, "matrixno").IsNotNullOrWhiteSpace().IsNotLongerThan(50);
            Condition.Requires<int>(modelRe.MaxConnectnum, "maxconnection").IsInRange(1,100);
            Condition.Requires<int?>(modelRe.Status, "status").IsNotNull().IsInRange(0, 1);
            #endregion CheckParmeter

            #region Deal


            var model = new psam_matrixModel();
            model.createip = IP;
            model.createtime = DateTime.Now;
            model.matrixip = modelRe.MatrixIP;
            model.matrixno = modelRe.MatrixNo;
            model.maxconnectnum = modelRe.MaxConnectnum;
            model.status = modelRe.Status;
            model.matrixport = modelRe.MatrixPort;
            model.id = Guid.NewGuid().ToString().Replace("-", "");
            var psammatrix = new BLL.psam_matrix();
            var ModelList=  psammatrix.GetModelList(" matrixno='"+ modelRe.MatrixNo + "' ");
            if (ModelList != null && ModelList.Count>0)
            {
                return SimpleResultHelper.SetDataExt(ErrorMsg.MsgMatrixNoExist,"矩阵编号存在");
            }
            if (!psammatrix.Add(model))
            {
                return SimpleResultHelper.SetDataExt(ErrorMsg.MsgSaveFail);
            }
            return SimpleResultHelper.SetDataForSuccess("", "成功");

            #endregion Deal
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="userID"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public Common.SimpleResult Edit(string appID, string userID, string postData)
        {
            #region CheckParmeter

            Condition.Requires(userID, "userID").IsNotNullOrWhiteSpace();//userID不能为空或者空字符串
            Condition.Requires(postData, "postData").IsNotNullOrWhiteSpace();//postData不能为空或者空字符串

            var modelRe = Newtonsoft.Json.JsonConvert.DeserializeObject<PSAMDeviceModel>(postData);//反序列化json对象
            Condition.Requires(modelRe.ID, "id").IsNotNullOrWhiteSpace().IsNotLongerThan(40);
            Condition.Requires(modelRe.MatrixIP, "matrixip").IsNotNullOrWhiteSpace().IsNotLongerThan(100);
            Condition.Requires(modelRe.MatrixPort, "matrixport").IsNotNullOrWhiteSpace().IsNotLongerThan(40);
            Condition.Requires(modelRe.MatrixNo, "matrixno").IsNotNullOrWhiteSpace().IsNotLongerThan(50);
            Condition.Requires<int>(modelRe.MaxConnectnum, "maxconnection").IsInRange(1, 100);
            Condition.Requires<int?>(modelRe.Status, "status").IsNotNull().IsInRange(0, 1);
            #endregion CheckParmeter

            #region Deal
            var psammatrix = new BLL.psam_matrix();
            var model = psammatrix.GetModel(modelRe.ID);

            if (modelRe.MatrixNo != model.matrixno)
            {
                var ModelList = psammatrix.GetModelList(" matrixno='" + modelRe.MatrixNo + "' ");
                if (ModelList != null && ModelList.Count > 0)
                {
                    return SimpleResultHelper.SetDataExt(ErrorMsg.MsgMatrixNoExist, "矩阵编号存在");
                }
            }
            model.modifyip = IP;
            model.modifytime = DateTime.Now;
            model.matrixno = modelRe.MatrixNo;
            model.maxconnectnum = modelRe.MaxConnectnum;
            model.matrixip = modelRe.MatrixIP;
            model.matrixport = modelRe.MatrixPort;
            model.status = modelRe.Status;

            
            if (!psammatrix.Update(model))
            {
                return SimpleResultHelper.SetDataExt(ErrorMsg.MsgSaveFail);
            }
            return SimpleResultHelper.SetDataForSuccess("", "成功");

            #endregion Deal
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="userID"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public Common.SimpleResult Del(string appID, string userID, string postData)
        {
            #region CheckParmeter

            Condition.Requires(userID, "userID").IsNotNullOrWhiteSpace();//userID不能为空或者空字符串
            Condition.Requires(postData, "postData").IsNotNullOrWhiteSpace();//postData不能为空或者空字符串

            var modelRe = Newtonsoft.Json.JsonConvert.DeserializeObject<PSAMDeviceModel>(postData);//反序列化json对象
            Condition.Requires(modelRe.ID, "id").IsNotNullOrWhiteSpace().IsNotLongerThan(40);

            #endregion CheckParmeter

            #region Deal
            var psammatrix = new BLL.psam_matrix();
            var model = psammatrix.GetModel(modelRe.ID);
            if (model == null)
            {
                return SimpleResultHelper.SetData(ErrorMsg.MsgInvalidLaneID, "加密矩阵id不存在");
            }
            else
            {
                if (!psammatrix.Delete(modelRe.ID))
                {
                    return SimpleResultHelper.SetDataExt(ErrorMsg.MsgSaveFail);
                }
            }

            return SimpleResultHelper.SetDataForSuccess("", "成功");

            #endregion Deal
        }

        /// <summary>
        /// 查询车道记录(分页)
        /// </summary>
        /// <param name="appID"></param>
        /// <param name="userID"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public Common.SimpleResult Search(string appID, string userID, string postData)
        {
            Condition.Requires(userID, "userID").IsNotNullOrWhiteSpace();//userID不能为空或者空字符串
            Condition.Requires(postData, "postData").IsNotNullOrWhiteSpace();//postData不能为空或者空字符串

            var modelRe = JsonConvert.DeserializeObject<PSAMDeviceSearchModel>(postData);//反序列化json对象
            Condition.Requires<int>(modelRe.pagesize, "pagesize").IsInRange(1, 100);
            if (modelRe.Status != null)
            {
                Condition.Requires<int?>(modelRe.Status, "status").IsInRange(0, 1);
            }
            #region Deal

            string strWhere = "1=1 ";

            if (!string.IsNullOrWhiteSpace(modelRe.MatrixNo))
            {
                strWhere += " and matrixno='{0}'";
                strWhere = string.Format(strWhere, modelRe.MatrixNo);
            }

            if (!string.IsNullOrWhiteSpace(modelRe.MatrixIP))
            {
                strWhere += " and matrixip='{0}'";
                strWhere = string.Format(strWhere, modelRe.MatrixIP);
            }

            if (modelRe.Status != null)
            {
                strWhere += " and status='{0}'";
                strWhere = string.Format(strWhere, modelRe.Status);
            }

            if (modelRe.CreateTime1 != null)
            {
                strWhere += " and createtime >= '{0}'";
                strWhere = string.Format(strWhere, modelRe.CreateTime1.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            if (modelRe.CreateTime2 != null)
            {
                strWhere += " and createtime <= '{0}'";
                strWhere = string.Format(strWhere, modelRe.CreateTime2.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            var bizLane = new psam_matrix();

            var result = new Model.Entity.baseresponse<PSAMDeviceResponseModel>();
            int total = bizLane.GetRecordCount(strWhere);
            if (total <= 0)
            {
                return SimpleResultHelper.SetDataForSuccess(result, "无数据");
            }
            result.total = total;

            DataSet dst = null;
            if (modelRe.pageindex <= 0 || modelRe.pagesize > 100)
            {
                dst = bizLane.GetList(strWhere);
            }
            else
            {
                dst = bizLane.GetListByPage(strWhere, " createtime desc ", modelRe.pagesize, modelRe.pageindex);
            }

            List<psam_matrixModel> listEntry = bizLane.DataTableToList(dst.Tables[0]);
            for (int i = 0; i < listEntry.Count; i++)
            {
                var model = listEntry[i];
                result.rows.Add(new PSAMDeviceResponseModel()
                {
                    CreateIP = model.createip,
                    CreateTime = model.createtime,
                    MatrixNo = model.matrixno,
                    ID = model.id,
                    ModifyIP = model.modifyip,
                    ModifyTime = model.modifytime,
                    MatrixIP = model.matrixip,
                    MatrixPort = model.matrixport,
                    MaxConnectnum = model.maxconnectnum,
                    Status = model.status
                });
            }

            return SimpleResultHelper.SetDataForSuccess(result, "成功");

            #endregion Deal
        }
    }
}
